<?php

class ReviewsController extends AppController
{
	var $name = "Reviews";
	var $helpers = array('Form', 'Html', 'Cms.Index', 'Comments.Comment', 'Rating.rating',);
	var $components = array('Auth', 'RequestHandler','Session','Email');
	
	var $indexMethods = array(); // shifted to bootstrap.php
	protected $autoAdminActions = array('admin_bulkDelete','admin_bulkPublish','admin_bulkUnpublish');

	function beforeFilter()
	{
		$this->Auth->allow('add','index','view','userReview','listingReview');
		parent::beforeFilter();
		
		$this->indexMethods = cr('indexMethods.Reviews');
	}
	
	function add($listingId = null)
	{	
		$authedUser = $this->Session->read('Auth.User');
		$reviewConfig = array();
		$reviewConfig['ReviewConfig'] = cr('ReviewConfig');	
		
		if($reviewConfig['ReviewConfig']['guest_write_review'] == 0 && empty($authedUser))
		{
			$this->redirect($this->Auth->loginAction);
		}
		if($listingId == null || $this->Review->Listing->hasAny(array('id'=>$listingId)) == false)
		{
			$this->errorMsg(__("Invalid Url."));
			$this->redirect($this->referer());
		}
		$currentIp = Utility::getClientIP();
		if($reviewConfig['ReviewConfig']['check_ip_addresses'])
		{			
			if($this->Review->hasAny(array('Review.listing_id'=>$listingId,'Review.ip'=>$currentIp)))
			{
				$this->__invalidUrl('One review has been added with this ip address.',$this->referer());
			}			
		}
		
		$listCategoryId = $this->Review->Listing->field('list_category_id',array('id'=>$listingId));
		$this->Review->setCategoryId($listCategoryId);
		$this->Review->Listing->recursive = -1;
		$listing = $this->Review->Listing->findById($listingId);

		//check for review on own listings starts here.
		$stopReviewOnOwnListing = $reviewConfig['ReviewConfig']['stop_review_on_own_listing'];
		$isOwner = cr("ListingConfig.business_owner") && $this->Session->read("Auth.User.id") && $listing['Listing']['owner_id'] == $this->Session->read("Auth.User.id");
		if(($listing['Listing']['user_id'] == $authedUser['id'] && $stopReviewOnOwnListing == true) || $isOwner == true)
		{
			$this->errorMsg(__('Sorry, you can not review your own listing.'));
			$this->redirect($listing['Listing']['viewUrl']);
		}
		//check for review on own listings ends here.		
		
		if($this->Review->hasReviewed($listingId,$this->Session->read('Auth.User.id')))
		{
			$this->errorMsg(sprintf(__("You have already reviewed %s"),$listing['Listing']['title']));
			$this->redirect($listing['Listing']['viewUrl']);
		}
		$isEditor = $this->Review->User->isEditor($authedUser['id']);
		if($this->Review->hasEditorReviewed($listingId) && $isEditor)
		{
			$this->errorMsg(sprintf(__("One editor has already reviewed %s!"),$listing['Listing']['title']));
			$this->redirect($listing['Listing']['viewUrl']);
		}
			
		if($this->data)
		{
			$assets = array();
			if(isset($this->data['Review']['assets']))
			{
				$assets = $this->data['Review']['assets'];
			}
			unset($this->data['Review']['assets']);
			unset($this->data['ListingAsset']);
			$captchaVerified = true;
			$errorMsg = 'Your review could not be saved!';
			if($reviewConfig['ReviewConfig']['captha_on_guest_review'] && empty($authedUser))
			{
				if($this->verifyCaptcha($this->data['Review']['captcha']) == false)
				{
					$errorMsg = 'Invalid captcha code!';
					$captchaVerified = false;					
				}	
			}
			$this->data['Review']['user_id'] = $this->Session->read('Auth.User.id');
			$this->data['Review']['listing_id'] = $listingId;
			$this->data['Review']['ip'] = $currentIp;
			$this->Review->create();
			if($captchaVerified == true && $this->Review->saveAll($this->data,array('validate'=>'first')))
			{
				$moderateNewUserReview = $reviewConfig['ReviewConfig']['moderate_new_user_reviews'];
				$moderateNewEditorReview = $reviewConfig['ReviewConfig']['moderate_new_editor_reviews'];
				$successMsg = 'Your review has been published.';
				if($isEditor && $moderateNewEditorReview == true)
				{	
					$successMsg = 'Your review has been saved and will be published after moderation.';					
						
				}elseif($isEditor == false && $moderateNewUserReview == true)
				{
					$successMsg = 'Your review has been saved and will be published after moderation.';
				}
				$this->saveAssest($this->Review->id, $listingId, $assets);
				$this->__afterAdd($this->Review->id,$isEditor);
				$this->successMsg(__($successMsg));				
				$this->redirect($listing['Listing']['viewUrl']);
			}else
			{
				$this->errorMsg(__($errorMsg));			 
			}
		}
		$this->set('listing',$listing);
		$this->set('reviewConfig',$reviewConfig['ReviewConfig']);
		$this->pageTitle = sprintf(__('Add review for %s'),$listing['Listing']['title']);	
		$this->actionId = "reviewAdd";
	}
	private function saveAssest($reviewId,$listingId,$assets)
	{
		if(cr('ReviewConfig.upload_assets') && $assets && $this->Session->read("Auth.User.id"))
		{
			$ListingAsset = cri('ListingAsset');
			foreach($assets as $asset)
			{
				if(isset($asset['name']) && is_array($asset['name']) && isset($asset['name']['error']) &&  $asset['name']['error'] == 0)
				{
					$ListingAsset->create();
					$data = array($ListingAsset->alias => array('name'=>$asset['name'],'status'=>ListingAsset::PUBLISHED,'user_id'=> $this->Session->read("Auth.User.id"),'listing_id'=>$listingId));
					$ListingAsset->save($data);
				}
			}
			$this->Review->clearRecordCache($reviewId,'listing_asset_count');			
		}
	}
	function edit($id = null)
	{	
		if($this->referer() != '/'.$this->params['url']['url'])
		{
			$this->Session->write('referer',$this->referer());
		}
		$referer = $this->Session->read('referer');
		$reviewConfig = cr("ReviewConfig");
		$isAdmin = false;
		if(isset($this->params['admin']))
		{
			$isAdmin = true;
		}
		if($reviewConfig['allow_review_edit'] == false && $this->referer() == '/')
		{
			$this->__invalidUrl("You don't have permission to edit this review.");
		}
		$this->pageTitle = __('Edit');
		if($this->action == 'edit')
		{
			$authedUserId = $this->Session->read('Auth.User.id');
			$this->Review->recursive  = 0;
			$reviewData = $this->Review->findByIdAndUserId($id,$authedUserId);
			$this->set("reviewData",$reviewData);
			$this->set("listing",$reviewData);
			$isEditor = $this->Review->User->isEditor($authedUserId);
			if($this->Review->isEditorialReview($id) && $isEditor == false)
			{
				$this->__invalidUrl("You need to be upgraded as editor to edit this review.",$this->referer());				
			}
		}else
		{
			$reviewData = $this->Review->findById($id);
		}
	
		if(empty($reviewData))
		{
			$this->errorMsg(__("Invalid Url."));
			$this->redirect($referer);
		}
		$this->Review->setCategoryId($reviewData['Listing']['list_category_id']);
		if($this->data)
		{
			$assets = array();
			if(isset($this->data['Review']['assets']))
			{
				$assets = $this->data['Review']['assets'];
			}
			unset($this->data['Review']['assets']);
			$this->data['Review']['user_id'] = $reviewData['Review']['user_id'];
			$this->data['Review']['listing_id'] = $reviewData['Review']['listing_id'];
			$this->data['Review']['id'] = $id;
			$this->Review->id = $id;
			if($this->Review->saveAll($this->data,array('validate'=>'first')))
			{
				$this->saveAssest($reviewData['Review']['id'], $reviewData['Review']['listing_id'], $assets);
				//$isEditorialReview = $this->Review->isEditorialReview($id);
				$isEditor = $this->Review->User->isEditor($this->data['Review']['user_id']);
				if($isAdmin)
				{
					$successMsg = "Review has been edited.";
				}else
				{		
					$successMsg = "Your review has been edited.";
				}
				if($isAdmin == false)
				{
					$redirectUrl = array('controller'=>'reviews','action'=>'view',$reviewData['Review']['id']);
					if($isEditor && $reviewConfig['moderate_edited_editor_reviews'] == true)
					{
						$redirectUrl = array('controller'=>'reviews','action'=>'index','my');						 
						$successMsg = 'Your review has been edited and will be published after moderation.';
					}
					elseif($isEditor == false && $reviewConfig['moderate_edited_user_reviews'] == true)
					{
						$successMsg = 'Your review has been edited and will be published after moderation.';
						$redirectUrl = array('controller'=>'reviews','action'=>'index','my');
					}else
					{
						$redirectUrl = $redirectUrl;
					}					
				}
				
				$this->successMsg(__($successMsg));
				if($isAdmin)
				{
					$redirectUrl = array('controller'=>'reviews','action'=>'admin_index');	
				}
				$this->redirect($redirectUrl);
			}
		}
		if(empty($this->data))
		{
			$this->data = $reviewData;
		}
		if(cr('ReviewConfig.upload_assets') && cr('ListingConfig.allow_asset_edit') && $this->params['action'] == "edit")
		{
			$listingAssets = cri("ListingAsset")->find("all",array("recursive"=>-1,'conditions'=>array('listing_id'=>$reviewData['Review']['listing_id'],"user_id"=>$this->Session->read("Auth.User.id"),'status'=>ListingAsset::PUBLISHED)));
			$this->set("listingAssets",$listingAssets);
			$this->helpers[] = "Assets.Asset";
		}
		$this->set('reviewConfig',$reviewConfig);
		$this->render('add');
	}
	
	function admin_edit($id = null)
	{	
		if($this->data)
		{
			$this->data['Review'] = $this->_appendAdminField($this->data['Review']);
		}
		$this->edit($id);		
	}
	
	function index($type = false)
	{
		$reviewConfig['ReviewConfig'] = cr('ReviewConfig');	
		$paginateLimit = $reviewConfig['ReviewConfig']['paginate_limit'];
		
		if($this->params['isAjax'] == 1)
		{
			Configure::write('debug',0);
		}
		$this->pageTitle = __('Reviews');
		$this->Review->setScope('published');
		
		$this->paginate['limit'] = $paginateLimit;
		$this->paginate['recursive']  = 0;
		$this->paginate['order'] = array('Review.created DESC');
			$this->Review->unbindModel(array('belongsTo'=>array('User','Guest')),false);	
		if($type)
		{
			if(in_array($type, array_keys($this->indexMethods)))
			{
				$subMethodName = $this->indexMethods[$type]['method'];
				if(isset($this->indexMethods[$type]['title']))
				{
					$this->pageTitle = __($this->indexMethods[$type]['title']);
				}
				$limit = null;
				if(isset($this->params['named']['limit']))
				{
					$limit = $this->params['named']['limit'];
				}
				$this->{$subMethodName}($limit);
			}
			else
			{
				$this->errorMsg(__("Invalid URL"));
				$this->redirect("/");
			}
		}
		$reviews = $this->paginate();
		if($this->_isVarRequest())
		{
			return $reviews;
		}
		array_push($this->helpers,  'Votes.Vote');
		if(!isset($this->params['requested']) || !$this->params['requested'])
		{
			$this->actionId = "reviewIndex";
		}
		$this->_setViewType($reviewConfig['ReviewConfig']);
		$this->set(compact('reviews'));
	}
	
	function _setViewType($reviewConfig)
	{
		$view_type = $reviewConfig['view_type'];
		if((isset($this->params['pass']['0']) && $this->params['pass']['0'] == 'search'))
		{
			//$view_type = 'table_view';
		}elseif(isset($this->params['requested']) && $this->params['requested'] == 1)
		{
			$view_type = 'blog_view';
		}		
		$this->set("view_type",$view_type);
	}
	
	/**
	 * Index Sub-methods starts from here
	 */
	
	function __newReviews()
	{
		$this->paginate['order'] = array('Review.created DESC');
	}
	
	function __myReviews()
	{
		$userId = $this->Session->read('Auth.User.id');
		if(empty($userId))
		{
			$this->__invalidUrl();
		}
		$this->paginate['conditions'][] = array('Review.user_id' => $userId);
	}	
	
	function __userReviews()
	{
		if(!isset($this->params['named']['user']))
		{
			$this->__invalidUrl('Invalid parameter passed.');
		}
		$userSlug = $this->params['named']['user'];
		$user = $this->Review->User->find('first',array('conditions'=>array('User.slug'=>$userSlug),'recursive'=>-1));
		if(empty($user))
		{
			$this->__invalidUrl();
		}
		$this->set('user',$user);					
		$this->paginate['conditions'][] = array('Review.user_id' => $user['User']['id']);
		$this->pageTitle = sprintf(__('%s\'s Reviews'),$user['User']['display_name']);
	}	
		
	function __listingReviews()
	{
		if(!isset($this->params['named']['listingId']))
		{
			$this->__invalidUrl();
		}
		$listingId = $this->params['named']['listingId'];
		$listingData = $this->Review->Listing->find('first',array('conditions'=>array('Listing.id'=>$listingId),'recursive'=>-1));
		if(empty($listingData))
		{
			$this->__invalidUrl();
		}	
		//set category for refreshing schema.
		$this->Review->setCategoryId($listingData['Listing']['list_category_id'],true);
		
		$this->paginate['conditions'][] = array('Review.listing_id'=> $this->params['named']['listingId']);
		//if(cr('GeneralConfig.disable_editor_reviews')!= 1)	//#6401 - commented this condition as it is resulting in incorrect review count
		//{
			$this->paginate['conditions']['not'] = array('Review.is_editorial'=>1);
		//}
		$this->pageTitle = sprintf(__("%s's Reviews"),$listingData['Listing']['title']);
		if(!isset($this->paginate['limit']) || $this->paginate['limit'] != 20)
		{
			$this->paginate['limit'] = 20;
		}
	}
	
	function __mostPopularReviews()
	{
		$voteObj = cri('Votes.Vote');
		$reviewIds = $voteObj->getTopRated('Review');
		$this->paginate['conditions'][] = array('Review.listing_id'=> $reviewIds);
		if(!empty($reviewIds))
		{
			$this->paginate['order'] = array('FIELD(Review.id,'.implode(',',$reviewIds).')');
		}	
	}
	
	function __topRatedReviews()
	{
		$this->paginate['order'] = array("Review.avg_score DESC");
	}
	
	function __mostViewedReviews()
	{
		$this->paginate['order'] = array('Review.views_count DESC');	
	}
	
	function __mostCommentedReviews()
	{
		$reviewIds = $this->Review->ReviewComment->getMostCommented();
		$this->paginate['conditions'][] = array('Review.id'=> $reviewIds);
		if(!empty($reviewIds))
		{
			$this->paginate['order'] = array('FIELD(Review.id,'.implode(',',$reviewIds).')');
		}	
	}
	function __featuredReviews($limit)
	{
		if(is_null($limit))
		{
			$limit = 1;
		}
		$featuredReviewIds = $this->Review->getLastFeatured($limit);
		$order = array();
		if($featuredReviewIds)
		{
			$order = array('FIELD(Review.id,'.implode(',',$featuredReviewIds).')');
		}
		$this->paginate['conditions'][] = array('Review.id'=>$featuredReviewIds,'Review.status'=>Review::PUBLISHED);
		$this->paginate['order'] = $order;			
	}
	
	function __invalidUrl($msg = null, $url = null)
	{
		if(empty($msg))
		{
			$msg = "Invalid URL";
		}
		if(empty($url))
		{
			$url = "/";
		}
		$this->errorMsg(__($msg));
		$this->redirect($url);
	}
	function __search()
	{
		$search = "";
		if(isset($this->params['named']['search']) && strlen($this->params['named']['search']) > 0)
		{
			$search = $this->params['named']['search'];
		}
		$condition = array();
		if(strlen($search) < 1)
		{
			$this->__newReviews();
		}else
		{
			$condition = $this->Review->getTextSearchCondition($search);
			$this->pageTitle= __("Result for \"$search\"");
		}
		//prd($condition);
		$this->paginate['conditions'] = $condition;
	}
	function view($id = null)
	{
		if($this->params['isAjax'] == '1' || (isset($this->params['url']['ajax']) && $this->params['url']['ajax'] == 1))
		{
			$this->layout = 'ajax';
			Configure::write('debug',0);
		}
		$this->actionId = "reviewView";
		$this->Review->recursive= 0;
		$this->Review->setEavStatus(true);
		$review = $this->Review->find('first',array('conditions'=>array('Review.id'=>$id,'Review.status'=>Review::PUBLISHED)));
		//set category for refreshing schema.
		$this->Review->setCategoryId($review['Review']['list_category_id'],true);
		$this->Review->setEavStatus(false);
		if(empty($review))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect(array('controller'=>'reviews','action'=>'index'));
		}
		
		$this->Review->id = $id;
		$this->Review->saveField('views_count',$review['Review']['views_count']+1, false, false);
		array_push($this->helpers,  'Votes.Vote');
		$this->pageTitle = sprintf(__('%s Reviews'),$review['Listing']['title']);
		$this->set('listing',array('Listing'=>$review['Listing']));
		$this->set('review', $review);
		$this->set("metaInformation",cri("MetaInformation")->getMetaInformation($this->Review->alias,$id));
		
		//for canonical URL
		$this->set('metaCanonicalUrl',$review['Review']['viewUrl']);
	}


	function admin_change_feature_status($id)
	{
		if($id)
		{
			$action='remove';
			$featureValue = $this->Review->field('is_featured',array('id'=>$id));
			if($featureValue != 1)
			{
				$action = 'add';
			}
			if($action == 'add')
			{
				$this->Review->makeFeatured($id);
			}
			if($action=='remove')
			{
				$this->Review->removeFeatured($id);
			}
			$this->successMsg(__('Your action has been performed'));
		}
		$this->redirect($this->referer());
	}
	
	function _appendAdminField($data)
	{
		$data['admin'] = true;
		return $data;
	}

	function admin_index()
	{
		if(isset($this->params['named']['search']))
		{
			$this->admin_search();	
		}else
		{
			$this->pageTitle = __('Reviews');
			$this->paginate['order'] = array('Review.created DESC');
			$this->paginate['limit'] = 10;
			$reviewData = $this->paginate();
			$this->set('reviewData',$reviewData);
		}
	}

	function admin_delete($id)
	{
		if($this->Review->del($id))
		{
			$this->successMsg(__('Review has been deleted.'));
		}else
		{
			$this->errorMsg(__('Review could not be deleted.'));
		}
		$this->redirect($this->referer());
	}

	function admin_changeStatus($id = null)
	{
		$listingData = $this->Review->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
		if(empty($listingData))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}
		$listingStatus = $listingData['Review']['status'];
		if($listingStatus == Review::PUBLISHED)
		{
			$statusToSave = Review::UNPUBLISHED;
			$successMessage = 'Review has been unpublished.';
			$errorMessage = 'Review could not be unpublished.';
		}
		else
		{
			$statusToSave = Review::PUBLISHED;
			$successMessage = 'Review has been published.';
			$errorMessage = 'Review could not be published.';
		}
		$this->Review->id = $id;
		if($this->Review->saveField('status',$statusToSave))
		{
			if($statusToSave == Review::PUBLISHED)
			{
				$this->__sendApprovalEmail($id);
			}else
			{
				//$this->Review->unpublishAssociatedEntity($id);
			}
			$this->successMsg(__($successMessage));
		}
		else
		{
			$this->errorMsg(__($errorMessage));
		}
			
		$this->redirect($this->referer());
	}
	
	function __afterAdd($id,$isEditor = false)
	{
		$sendApprovalEmail = false;
		if($isEditor && cr('ReviewConfig.moderate_new_editor_reviews') == '1')
		{
			$sendApprovalEmail = true;
		}elseif(cr('ReviewConfig.moderate_new_user_reviews') == '1')
		{
			$sendApprovalEmail = true;
		}
		
		$this->__sendApprovalEmail($id,$sendApprovalEmail);
		
	}
	
	function __sendApprovalEmail($params,$sendApprovalEmail = true)
	{
		if(is_numeric($params))
		{
			$this->Review->recursive = 0;
			$reviewData = $this->Review->findById($params);
			$userData = $reviewData['Review']['poster'];			
		}else
		{
			$reviewData = $params;
			$userData = $this->Session->read('Auth.User');
		} 
		
		$emailStatus = $this->Review->User->hasAny(array("onAddedReviewApproval"=>1,'User.id'=>$userData['id']));
		if($reviewData['Review']['status'] == Review::PUBLISHED)
		{
			//settting varibles for email templates
			$viewUrl = cr('cmsConfig.Backend.siteUrl').'/reviews/view/'.$reviewData['Review']['id'];
			$listingTitle = $reviewData['Listing']['title'];
				
			$this->set('reviewUrl',$viewUrl);
			$this->set('listingTitle',$listingTitle);
			$this->Review->id = $reviewData['Review']['id'];			
			if($emailStatus == 1 && $sendApprovalEmail == true)
			{
				$this->Email->to = $userData['email'];
				$this->Email->subject = __('Review Published');
				$this->Email->setFrom(cr('cmsConfig.Backend.websiteEmail'),cr('cmsConfig.Backend.siteName'));
				$this->Email->sendAs = 'both';
				$this->Email->template = 'added_review_approval';
								
				$viewUrl = cr('cmsConfig.Backend.siteUrl').'/reviews/view/'.$reviewData['Review']['id'];
				$listingTitle = $reviewData['Listing']['title'];
				$this->set('username',$userData['display_name']);
				$this->Email->send();			
			}		
			if($reviewData['Review']['published_email_sent'] == 1)
			{
				return;
			}
			//Flag that email has been sent.
			$this->Review->saveField('published_email_sent',1);
			App::import('Vendor', 'EmailOperation');
				
			//*****code for afterFavListingReveiw starts here****//
					
			$favListingUserList = $this->Review->User->find('all',array('conditions'=>array('NOT'=>array('User.id'=>$reviewData['Review']['user_id']),'User.onFavListingReviewed'=>1),'recursive'=>-1));
			if($favListingUserList)
			{
				$favListingUserList = Set::combine($favListingUserList,'{n}.User.id','{n}.User');
			}
			$userFavoriteList = ClassRegistry::init('Users.UserFavorite')->find('list',array('fields'=>array('id','user_id'),'conditions'=>array('item_id'=>$reviewData['Review']['listing_id'],'type'=>'Listing')));
			$this->set('reviewer',$userData['display_name']);
			
			EmailOperation::sendMail('mailAfterFavListingReviewed',array($this,$userFavoriteList,$reviewData,$favListingUserList));
			//*****code for afterFavListingReveiw ends here****//
			
			//*****code for afterReviewdListingReviewed starts here****//
			$userList = $this->Review->User->find('all',array('conditions'=>array('NOT'=>array('User.id'=>$reviewData['Review']['user_id']),'User.onReviewedListingReview'=>1),'recursive'=>-1));
			$sendingMailIds = array();
			if($userList)
			{
				$userIdList = Set::extract('{n}.User.id',$userList);
				$sendingMailIds = $this->Review->find('list',array('fields'=>array('id','user_id'),'conditions'=>array('Review.listing_id'=>$reviewData['Review']['listing_id'],'Review.user_id'=>$userIdList)));
				$userList = Set::combine($userList,'{n}.User.id','{n}.User');
			}				
			EmailOperation::sendMail('mailAfterReveiwPublish',array($this,$sendingMailIds,$reviewData,$userList));
			//*****code for afterReviewdListingReviewed ends here****//
		}
	}
	
	function admin_search()
	{
		$default = array(
			'title'=>'',
			'submitter_name'=>'',
			'list_category_id'=>'',
			'status'=>'',
		);	
		if($this->data)
		{
			$queryString = '';
			foreach($this->data['Review'] as $field=>$value)
			{
				$queryString .= $field.':'.$value.'/';
			}		
			$this->redirect('/admin/reviews/search/'.$queryString);
		}		
			
		$params = am($default,$this->params['named']);
		if(!empty($params['title']))
		{
			$this->paginate['conditions']['AND'][] = array('Review.title LIKE'=>'%'.$params['title'].'%');	
		}
			
		if(!empty($params['submitter_name']))
		{
			if($params['status'] != 'guest_review')
			{
				$user_ids = $this->Review->User->find('list',array('fields'=>'User.id','conditions'=>array('username LIKE'=>'%'.$params['submitter_name'].'%')));
				$this->paginate['conditions']['AND'][] = array('Review.user_id'=>$user_ids);
			}
			
			$guest_ids = $this->Review->Guest->find('list',array('fields'=>'Guest.id','conditions'=>array('Guest.name LIKE'=>'%'.$params['submitter_name'].'%')));
			$this->paginate['conditions']['AND'][] = array('Review.guest_id'=>$guest_ids);
		}
			
		if(!empty($params['list_category_id']))
		{
			$categoryIds = $params['list_category_id'];
			$this->paginate['conditions']['AND'][] = array('Review.list_category_id'=>$categoryIds );	
		}
			
		if($params['status'] !=='')
		{
			if($params['status'] == 'user_review')
			{
				$this->paginate['conditions']['AND'][] = array('Review.is_editorial'=>0);
						
			}elseif($params['status'] == 'editor_review')
			{
				$this->paginate['conditions']['AND'][] = array('Review.is_editorial'=>1);
			
			}elseif($params['status'] == 'featured')
			{
				$this->paginate['conditions']['AND'][] = array('Review.is_featured'=>1);		
			}
			elseif($params['status'] == 'guest_review')
			{
				$this->paginate['conditions']['AND'][] = array('Review.user_id'=>null);
			}
			else
			{
				$this->paginate['conditions']['AND'][] = array('Review.status'=>$params['status']);
			}
		}		
		
		$this->paginate['contain'] = array('ListCategory');
		$this->paginate['order'] = array('Review.created DESC');
		$this->paginate['limit'] = 10;
		if(isset($this->params['named']['page']) || isset($this->params['named']['limit']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
		}elseif(isset($this->paginate['conditions']))
		{
			$this->Session->write('searchParams',$params);
			$this->Session->write('conditions',$this->paginate['conditions']);
		}
		$reviewData = $this->paginate();	
		$this->set('reviewData',$reviewData);
		$this->render('admin_index');
	}
	
	function admin_view($id = null)
	{
		$reviewData = $this->Review->findById($id);
		$this->Review->setEavStatus(true);
		$this->set(compact('reviewData'));
	}
}
?>